package org.grayrabbit.cms.freemarker.tpl.config;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import org.grayrabbit.service.GenericService;

import freemarker.template.Configuration;
import freemarker.template.TemplateModelException;

public class PopulateFtlData {
	private  static Logger log = LoggerFactory.getLogger(PopulateFtlData.class);
	
	public static void initFreemarkerConfiguration(Properties props, ApplicationContext context, Configuration configuration) {
		initFreemarker(props, configuration);
		initSpringData( context, configuration);
		setConfigurationVar(configuration);
	}
	
	public static void initFreemarkerConfiguration(ApplicationContext context, Configuration configuration) {
		Properties prop = new Properties();
		try {
			InputStream stream =PopulateFtlData.class.getResourceAsStream("/tpl.properties");
			prop.load( stream );
		} catch(Exception e) {
			log.error("加载tpl出错",e);
		} 
		initFreemarkerConfiguration(prop, context, configuration);
	}
	
	private static void setConfigurationVar(Configuration configuration) {
		try {
			configuration.setSharedVariable("freemarker_configuration", configuration);
		} catch (TemplateModelException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	//修改了读属性文件内容限原定义数组限制，去除限制，edited by sys53 on 2011.6.17
	private static void initFreemarker(Properties props, Configuration configuration) {
		
		try {
			for(Object key : props.keySet()) {
				Object value = props.get(key);
				configuration.setSetting((String) key, (String) value);
			}
			// configuration.setDirectoryForTemplateLoading( templateRoot ); 模板根目录
		} catch(Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	public static void  initFreemarkerConfiguration(Configuration configuration){
		Properties prop = new Properties();
		try {
			InputStream stream =PopulateFtlData.class.getResourceAsStream("/tpl.properties");
			prop.load( stream );
		} catch(Exception e) {
			throw new ExceptionInInitializerError(e);
		} 
		initFreemarker(prop,configuration);
	}
	private static void initSpringData( ApplicationContext context, Configuration configuration) {
		
		try {
			String[] serviceNames = context.getBeanNamesForType(GenericService.class);
			Map<String, Object> serviceMap = new HashMap<String, Object>();
			for(String e : serviceNames) {
				serviceMap.put(e, context.getBean(e));
			}
			configuration.setSharedVariable("spring", serviceMap); 
			
			//页面需要的特殊处理的 方法 可以在这里添加
			// 例如： configuration.setSharedVariable("pad_left_spt", new PadLeftSptMethod());
			
		} catch(Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
}
